//
//  RecommendViewController.swift
//  CompareToBuy
//
//  Created by 唐先才 on 16/1/26.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import Foundation
import UIKit

class RecommendViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var _collectionView: UICollectionView?
    var _head: UICollectionReusableView?
    var button: UIButton?
    var headView: UIImageView?
    var headCollect: UICollectionReusableView?
    var rollingCollect: UICollectionView?
    var _dataArray1: NSMutableArray = []
    var _dataArray2: NSMutableArray = []
    var _dataArray3: NSMutableArray = []
    var _dataArray4: NSMutableArray = []
    var _page: NSInteger = 0
    var _isPulling: Bool?
    var viewController: UIViewController?
    var isAnimation: Bool = false
    var lastContentOffsetY: CGFloat = 0
    var waitView: WaitLoadView?
    
    override func viewWillAppear(animated: Bool) {
    }
    
    override func viewDidLoad() {
        self._page = 1
        self.createData()
        self.createCollectionView()
        self.createRefresh()
        waitView = WaitLoadView(frame: self.view.frame)
        guard let waitView = self.waitView else {
            print("调用正在加载失败")
            return
        }
        self.view.addSubview(waitView)
    }
    
    func createData() {
        if _isPulling == true {
            self._dataArray4.removeAllObjects()
        }
        self._dataArray1.removeAllObjects()
        self._dataArray2.removeAllObjects()
        self._dataArray3.removeAllObjects()
        
        let manager: AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
        let parameters1 = ["infoNation": "0",
                           "mallUrl": ""]
        //partOne:
        manager.POST(scrollerView_url, parameters: parameters1, success: { (operation: AFHTTPRequestOperation!,
            responseObject: AnyObject?) -> Void in
            guard let waitView = self.waitView else {
                print("调用正在加载失败")
                return
            }
            waitView.removeFromSuperview()
//            swift 解包时需判断返回数据的类型
//            if let array = responseObject as? [[String: AnyObject]] {
//                print("----------- \(array)")
//            }
            //虽然是AnyObject类型的 但是要用数组接收的话需要确定其每个元素的数据类型
            guard let array1 = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict1 in array1 {
                let model = TxcModel.modelWithDict(dict1)
                self._dataArray1.addObject(model)
            }
            }) { (operation: AFHTTPRequestOperation!,
                error: NSError!) -> Void in
                
        }
        
        //partTwo:
        manager.POST(button_url, parameters: nil, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array2 = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict2 in array2 {
                let model = TxcModel.modelWithDict(dict2)
                self._dataArray2.addObject(model)
            }
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                
        }
        
        //partThree:
        let parameters3 = ["p_btSpecialType": "0",
                           "p_iPageIndex": "1",
                           "p_iPageSize": "5",
                           "p_iParentSpecialID": "0",
                          ]
        manager.POST(special_url, parameters: parameters3, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array3 = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict3 in array3 {
                let model = TxcModel.modelWithDict(dict3)
                self._dataArray3.addObject(model)
            }
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                
        }
        
        //partFour:
        let parameters4 = ["brightUrl": "",
                           "catUrl": "",
                           "exceptMallUrl": "",
                           "homeShow": "1",
                           "infoNation": "0",
                           "infoType": "0",
                           "isTop": "1",
                           "keyWord": "",
                           "mallUrl": "",
                           "pageIndex": self._page,
                           "pageSize": "20",
                           "tagUrl": "",
                          ]
        manager.POST(collection_url, parameters: parameters4, success: { (operation:AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array4 = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict4 in array4 {
                let model = TxcModel.modelWithDict(dict4)
                self._dataArray4.addObject(model)
            }
            guard let _collectionView = self._collectionView else {
                print("刷新失败4")
                return
            }
            _collectionView.reloadData()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in

        }
    }
    
    func createCollectionView() {
    
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .Vertical
        _collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: HEIGHT - 80), collectionViewLayout: layout)
        guard let _collectionView = _collectionView else {
            return
        }
        _collectionView.backgroundColor = BACKGROUD_COLOR
        self.view.addSubview(_collectionView)
        _collectionView.dataSource = self
        _collectionView.delegate = self
        _collectionView.showsVerticalScrollIndicator = false
        
//       非xib的写法，注意调用本类使用.self
//        _collectionView!.registerClass(ScrollViewCell.self , forCellWithReuseIdentifier: "scrollViewCell")
        _collectionView.registerClass(RollCollectionViewCell.self, forCellWithReuseIdentifier: "rollCollectionViewCell")
        let nib2 = UINib(nibName: "ButtonCell", bundle: NSBundle.mainBundle())
        _collectionView.registerNib(nib2, forCellWithReuseIdentifier: "buttonCell")
        let nib3 = UINib(nibName: "SpecialCell", bundle: NSBundle.mainBundle())
        _collectionView.registerNib(nib3, forCellWithReuseIdentifier: "specialCell")
        let nib4 = UINib(nibName: "CollectionCell", bundle: NSBundle.mainBundle())
        _collectionView.registerNib(nib4, forCellWithReuseIdentifier: "collectionCell")
        _collectionView.registerClass(CollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "head")

    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 4
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if section == 0 {
            return 1
        } else if section == 1 {
            return self._dataArray2.count
        } else if section == 2 {
            return self._dataArray3.count
        }
        return self._dataArray4.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            let rollCollectionViewCell = RollCollectionViewCell.rollCollectionViewCellWithCollectionView(collectionView, dataArray: self._dataArray1, indexPath: indexPath)
            return rollCollectionViewCell
        } else if indexPath.section == 1 {
            let cell = ButtonCell.buttonCellWithCollectionView(collectionView, dataArray: self._dataArray2, indexPath: indexPath)
            return cell
        } else if indexPath.section == 2 {
            let specialCell = SpecialCell.specialCellWithCollectionView(collectionView, dataArray: self._dataArray3, indexPath: indexPath)
            return specialCell
        } else {
            let collectionCell = CollectionCell.collectionCellWith(collectionView, dataArray: self._dataArray4, indexPath: indexPath)
            return collectionCell
        }
    }
        
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSize(width: WIDTH, height: 200)
        } else if indexPath.section == 1 {
            return CGSize(width: (WIDTH - 40) / 4, height: 80)
        } else if indexPath.section == 2 {
            return CGSize(width: WIDTH, height: 360)
        } else if indexPath.section == 3 {
            return CGSize(width: (WIDTH - 20) / 2, height: 320)
        }
        return CGSizeZero
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        if section == 3 {
            return UIEdgeInsetsMake(10, 5, 10, 5)
        }
        return UIEdgeInsetsZero
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        if indexPath.section == 3 && kind == UICollectionElementKindSectionHeader {
            guard let head = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "head", forIndexPath: indexPath) as? CollectionHeaderView else {
                return UICollectionReusableView()
            }
            head.backgroundColor = UIColor.whiteColor()
            return head
        }
        return UICollectionReusableView()
    }
   
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 3 {
            return CGSizeMake(WIDTH, 140)
        }
        return CGSizeZero
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.section == 0 {
            print("在rec点击的")
            let dvc = DetailViewController()
            self.navigationController?.pushViewController(dvc, animated: true)
        } else if indexPath.section == 1 {

        } else if indexPath.section == 2 {
            
        } else if indexPath.section == 3 {
            let dvc = DetailViewController()
            guard let model = self._dataArray4[indexPath.row] as? TxcModel else {
                print("向详情页传值错误")
                return
            }
            guard let infoID = model.InfoID else {
                return
            }
            dvc.goodsID = "\(infoID)"
            dvc.parameters = ["infoID": infoID]
            dvc.pic_url = model.MainImage
            guard let vc = self.viewController else {
                return
            }
            vc.navigationController?.pushViewController(dvc, animated: true)
        }
    }
    
    ///滑动的动画效果
    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.section != 3 {
            return
        }
        if isAnimation {
            startAnimation(cell, offsetY: 120, duration: 1.0)
        }
    }
    
    private func startAnimation(view: UIView, offsetY: CGFloat, duration: NSTimeInterval) {
        view.transform = CGAffineTransformMakeTranslation(0, offsetY)
        UIView.animateWithDuration(duration, animations: { () -> Void in
            view.transform = CGAffineTransformIdentity
        })
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.contentOffset.y <= scrollView.contentSize.height {
            isAnimation = lastContentOffsetY < scrollView.contentOffset.y
            lastContentOffsetY = scrollView.contentOffset.y
        }
    }
    
    ///创建刷新
    func createRefresh() {
        guard let _collectionView = self._collectionView else {
            print("创建刷新失败")
            return
        }
        _collectionView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "downRefresh")
        _collectionView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: "upRefresh")
    }
    
    func downRefresh() {
        guard let _collectionView = self._collectionView else {
            print("下拉刷新失败")
            return
        }
        _isPulling = true
        _collectionView.mj_header.beginRefreshing()
        self.createData()
        _collectionView.mj_header.endRefreshing()
    }
    
    func upRefresh() {
        guard let _collectionView = self._collectionView else {
            print("上载刷新失败")
            return
        }
        _isPulling = false
        self._page++
        self.createData()
        _collectionView.mj_footer.endRefreshing()
    }
}